// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const MAX_LIMIT = 100;
// 云函数入口函数
exports.main = async() => {
  console.log('函数被拉起，执行自动任务');
  const today = Date.parse(new Date().toLocaleDateString());
  //遍历所有任务
  const missionNumber = await db.collection('mission').count();
  const total = missionNumber.total;
  const times = Math.ceil(total / MAX_LIMIT);
  const allTasks = [];
  for (let i = 0; i < times; i++) {
    const listResponse = await db.collection('mission').field({
      _id: true,
      status: true
    }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    allTasks.push(...listResponse.data)
  }
  //检查过期情况
  for (const item of allTasks) {
    if (item.status !== 'done') {
      const res = await cloud.callFunction({
        name: 'getMissionInfo',
        data: {
          id: item._id
        }
      })
      const mission = res.result;
      if (mission.end) {
        const endDate = new Date(mission.end).getTime();
        if (endDate < today) {
          //用户超期
          // console.log('任务超期：', mission)
          const res = await sendMeg({
            userId: mission.userId,
            missionName: mission.name,
            status: (() => {
              switch (mission.status) {
                case 'delay':
                  return '已超期';
                case 'doing':
                  return '已超期';
                default:
                  return '已超期';
              }
            })(),
            endTime: mission.end
          })
          console.log(res)
        }
      }
    }
  }
  return;
}

function sendMeg(options) {
  const {
    userId,
    missionName,
    status,
    endTime
  } = options;
  console.log(options)
  return cloud.openapi.templateMessage.send({
    touser: userId, //用户id
    page: '/page/NX_index/index',
    templateId: 'UuPLr1aLp3c4SDcy-ozfg-LXPelJunUSsH_zuH5icPc',
    data: {
      keyword1: { //任务名称
        value: missionName
      },
      keyword2: { //任务状态
        value: status
      },
      keyword3: { //截止时间
        value: endTime
      }
    }
  })
}